#include "Message.h"
#include "Subscriber.h"

#include <algorithm>

Subscriber::Subscriber()
{
	;
}

Subscriber::~Subscriber()
{
	_lock();
	while(!m_message_queue.empty())
	{
		delete m_message_queue.front();
		m_message_queue.pop();
	}
	_unlock();
}

bool Subscriber::is_subscribed( int id ) const
{
	std::vector<int>::const_iterator beg, end;

	for(beg=m_subscription_ids.begin(), end=m_subscription_ids.end(); beg!=end; ++beg)
	{
		if(*beg)
			return true;
	}
	return false;
}

void Subscriber::add_subscription( int id )
{
	if(!is_subscribed(id))
	{
		m_subscription_ids.push_back(id);
	}
}

void Subscriber::remove_subscription( int id )
{
	std::vector<int>::iterator beg, end, del;

	// vector remove item
	beg=m_subscription_ids.begin();
	end=m_subscription_ids.end();
	del = std::remove(beg, end, id);
	m_subscription_ids.erase(del, end);
}

bool Subscriber::has_messages()
{
	_lock();
	bool ret = !m_message_queue.empty();
	_unlock();
	return ret;
}

void Subscriber::add_message( Message* message )
{
	_lock();
	m_message_queue.push(message);
	_unlock();
}

Message* Subscriber::get_message( )
{
	_lock();
	Message *ptr = m_message_queue.front();
	m_message_queue.pop();
	_unlock();
	return ptr;
}

void Subscriber::clear_messages()
{
	_lock();
	while(!m_message_queue.empty())
	{
		m_message_queue.pop();
	}
	_unlock();
}

void Subscriber::_lock()
{
	m_cs_message_queue.lock();
}

void Subscriber::_unlock()
{
	m_cs_message_queue.unlock();
}